import React,{Component} from 'react'
import {Row,Col,Menu,Spin,Table,Input,Select,notification } from 'antd'
import LeftMenus from './LeftMenu';
import CheckboxGroup from './CheckboxGroup'
const Option = Select.Option;
import EditableCell from './EditCell'

import {roleList,serviceList,updateRole,userTypeList} from '../../services/roleMana'
import './RoleMana.css'
class RoleMana extends Component{
    constructor(props){
        super(props)
        
    }
    state ={
        typeList:[],
        initData:[{}],
        menuArr:[],
        leftMenu:[],
        loading:true,
        checkboxArr:[],
        checkedList:[],
        selectedRow:'',
        rowData:[{}],
        isSelected:false,
        checkedArr:[],
        json:{}
    }
    componentDidMount(){
        roleList().then((data) => {
            this.setState({
                leftMenu:data.data,
                menuArr:data.data
            })
        });
        serviceList().then((data) => {
            const arr =[]
            data.data.map((item)=>{
                arr.push(item.service_name);
                
            })
            
            this.setState({
                checkboxArr:data.data,
                checkboxGroup:arr,
                loading:false
            })
          });
        
        userTypeList().then(data=>{
            this.setState({
                typeList:data.data,
                loading:false
            })
        })
    }
    
    handleClcik= (record, index, event)=>{
        
        const arr = this.state.checkboxArr
        let json = {}
        const that = this
        
        arr.map(item => {
            let checkedList = [];
            let listJson = {}
            const arr =[];
            item.action_list.map(data =>{ 
                const list = data.action_list;
                // const arr =[];
                list.map(data =>{
                    const allCheckedList = new Set(record.action_id_list)
                    if(allCheckedList.has(data.id)){
                        arr.push(data.id)
                    }
                })
                listJson[data.group_name] ={
                    "checked": arr
                }
            })
            json[item.service_name] = arr;
        })
        this.setState({
            checkedList:record.action_id_list,
            selectedRow:index,
            rowData:[record],
            isSelected:true,
            json:json
        })
        
    }
    rowClassName=(record, index,)=>{
        if(this.state.selectedRow === index){
          return 'rowSelected'
        }
        return '';
      }
    CheckboxChange(key,checkboxList){
        this.state.json[key] = checkboxList
        
     }

     getChecked=()=>{
        let checkedArr =[];
        for(let key in this.state.json){
            checkedArr = [...checkedArr,...this.state.json[key]]
        }
  
        return checkedArr
    }
    onmouseover=()=>{
        alert()
    }
    isNull =(obj)=>{
        for(let key in obj){
            return false
        }
        return true
    }
    save =(row)=>{
        if(this.isNull(row))  return;
        const data = {...row}
        data['action_id_list'] = this.getChecked().toString();
        updateRole(data).then(data=>{
            console.log(data,'123')
            if(data.status === 0){
                notification.success({
                    message: '保存成功！',
                  });
                const menuArr = this.state.menuArr;
                for(let i =0;i<menuArr.length;i++){
                    if(menuArr[i].id = data.data.id){
                        menuArr[i].action_id_list = data.data.action_id_list
                        return;
                    }
                }
            }else{
                notification.error({
                    message: '保存失败！',
                  });
            }
        })
        
    }
    handleChange(key, index, value) {

        const data = this.state.rowData
        data[index][key] = value;
        this.setState({
            rowData:data
        })
    }
    renderColumns(index, key, text) {
        return (<EditableCell
          value={text}
          onChange={value => this.handleChange(key, index, value)}
        />);
      }
      clean =()=>{
        this.setState({
            selectedRow:'',
            loading:false,
            rowData:[{}],
            isSelected:false,
            json:{}
        })
    }
    userTypeChange=(val, record, index)=>{
        const row = {...record}
        row['allowed_user_type'] = val,
      
        this.setState({
            rowData:[row]
        })
    }
    render(){
        const columns = [
            { title: '', dataIndex: 'display_name' , 
            render: (text, record) => {
              return (
                  <div >
                      {record.display_name}
                  </div>
                )
              
            }},
        ]

        const col = [
            { title: '角色名称',dataIndex: 'name',render: (text, record, index) => this.renderColumns(index, 'display_name',text)},
            { title: '显示名称',dataIndex: 'display_name',render: (text, record, index) => this.renderColumns(index, 'name',text)},
            { title: '排序',dataIndex: 'display_order',render: (text, record, index) => this.renderColumns(index, 'display_order',text)},
            { title: '允许类型',dataIndex: 'allowed_user_type',render: (text, record,index) => {
                if(this.state.typeList.length>0){
                    return (
                        <Select defaultValue={`${record.allowed_user_type?record.allowed_user_type:3}`} style={{ width: 120 }} onChange={(val)=>this.handleChange(record,val)}>
                            {
                                this.state.typeList.map(item =>{
                                    return (
                                        <Option key={item.id} value={`${item.id}`}>{item.description}</Option>
                                    )
                                })
                            }
                                
                        </Select>
                    )
                }
            }},
            { title: '描述',dataIndex: 'description',render: (text, record,index) => this.renderColumns(index, 'description',text)},
              { title: '',dataIndex: '',render: (text, record) => {
                  if(this.state.isSelected){
                      return (
                        <div>
                            <a onClick={()=>this.save(record)} style={{marginRight:'10px'}}>保存</a>
                            <a onClick={this.clean}>清空</a>
                        </div>
                      )
                  }
                return (
                    <a onClick={()=>this.save(record)}>保存</a>
                  )
                
              }},
        ]
        console.log(this.state.json,'json')
        return(
            <div className="myContainer" >
                <Spin spinning={this.state.loading}>
                <Row gutter={16}>
                    <Col span={4} >
                    <Table columns={columns} key="leftMenu"
                        onRowClick={this.handleClcik}
                        rowClassName={this.rowClassName}
                        rowKey={record => record.id}
                        dataSource={this.state.menuArr}
                        showHeader={false}
                        pagination={false}
                        bordered
                            />
                    </Col>
                    <Col span={20} >
                        
                        <Table columns={col} className="top-table" key="topTable"
                        rowKey={record => record.id?record.id:'topTablerow'}
                        dataSource={this.state.rowData}
                        pagination={false}
                        bordered
                            />
                        {
                            this.state.checkboxArr.map((item,index) =>{
                                return <CheckboxGroup onChange={this.CheckboxChange.bind(this)} key={index} checkboxArr={item}
                                checkedList={this.state.json[item.service_name]}  />
                            })
                        }
                        
                    </Col>
                </Row>
                </Spin>
            </div>
        )
    }
}

export default RoleMana
